package com.c7.bm.mybatis.util;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * Created by duke on 15/7/15.
 */
public class FileUtil {

    private static Logger logger = LogManager.getLogger(FileUtil.class);

    public final static String AT_NAME = "AT";
    public final static String THUM_NAME = "THUM";
    public final static String QR_NAME = "QR";
    public final static String LOGO_NAME = "LOGO";

    /**
     * 上传文件
     */
    public static void uploadFiles(MultipartFile file, String path) {
        InputStream inputStream = null;
        FileOutputStream outPutStream = null;
        try {
            inputStream = file.getInputStream();

            File f = new File(path);
            if (!f.exists()) {
                createFile(f);
            }
            outPutStream = new FileOutputStream(f);
            byte buffer[] = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) > 0) {
                //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                outPutStream.write(buffer, 0, len);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            try {
                outPutStream.flush();
                inputStream.close();
                outPutStream.close();
            } catch (Exception ex) {
                logger.error(ex);
            }
        }
    }

    /**
     * 分开路径名称上传文件
     *
     * @param file
     * @param filePath
     * @param fileName
     */
    public static void uploadFiles(MultipartFile file, String filePath, String fileName) {
        File f = new File(filePath);
        InputStream inputStream = null;
        FileOutputStream outPutStream = null;

        if (!f.exists()) {
            f.mkdirs();
        }

        f = new File(filePath + File.separator + fileName);
        try {
            if (!f.exists()) {
                f.createNewFile();
            } else {
                return;
            }
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            return;
        }

        try {
            inputStream = file.getInputStream();
            outPutStream = new FileOutputStream(f);
            byte buffer[] = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) > 0) {
                //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                outPutStream.write(buffer, 0, len);
            }
        } catch (Exception ex) {
            logger.error(ExceptionUtils.getStackTrace(ex));
            return;
        } finally {
            try {
                outPutStream.flush();
                inputStream.close();
                outPutStream.close();
            } catch (Exception ex) {
                logger.error(ExceptionUtils.getStackTrace(ex));
            }
        }


    }

    /**
     * 随机文件名
     *
     * @param name
     * @return
     */
    public static String getFileName(String name) {
        StringBuilder fileName = new StringBuilder(name).append("_");
        String time = StringUtil.getString(System.currentTimeMillis());
        fileName.append(time.substring(0, 4)).append(random(8));
        return fileName.toString();
    }

    /**
     * 创建目录
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static boolean createFile(File file) throws IOException {
        if (!file.exists()) {
            makeDir(file.getParentFile());
        }
        return file.createNewFile();
    }

    public static void makeDir(File dir) {
        if (!dir.getParentFile().exists()) {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }


    /**
     * 随机数
     *
     * @param n
     * @return
     */
    public static String random(int n) {
        if (n < 1 || n > 10) {
            throw new IllegalArgumentException("cannot random " + n + " bit number");
        }
        Random ran = new Random();
        if (n == 1) {
            return String.valueOf(ran.nextInt(10));
        }
        int bitField = 0;
        char[] chs = new char[n];
        for (int i = 0; i < n; i++) {
            while (true) {
                int k = ran.nextInt(10);
                if ((bitField & (1 << k)) == 0) {
                    bitField |= 1 << k;
                    chs[i] = (char) (k + '0');
                    break;
                }
            }
        }
        return new String(chs);
    }

    /**
     * 获取文件后缀名
     *
     * @param file
     * @return
     */
    public static String getSuffix(MultipartFile file) {
        String aa = file.getContentType();
        return "." + file.getContentType().split("/")[1];
//        return file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") - 1);
    }

    public static void main(String args[]) {
//        String filePath = "/Users/duke/image/item/aaa.txt";
//        File file = new File(filePath);
//        try {
//            System.out.println("file.exists()? " + file.exists());
//            boolean created = createFile(file);
//            System.out.println(created?"File created":"File exists, not created.");
//            System.out.println("file.exists()? " + file.exists());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        System.out.println(getFileName("PT"));
    }
}
